mod common;
mod config;
mod tray;

use crate::command;
use std::error::Error;
use tauri::webview::PageLoadPayload;
use tauri::{async_runtime::spawn, App};
use tauri::{Manager, Window, WindowEvent};

pub fn setup(app: &mut App) -> Result<(), Box<dyn Error>> {
    let handle = app.handle();
    spawn(config::init(handle.clone()));

    if let Err(e) = tray::init(handle.clone()) {
        log::error!("setup_tray error: {}", e);
    }

    Ok(())
}

pub fn window_event_handler(win: &Window, event: &WindowEvent) {
    let app = win.app_handle();
    match event {
        WindowEvent::CloseRequested { .. } => {
            if let Err(e) = common::app_exit(app) {
                log::error!("{}", e);
            }
        }
        _ => {}
    }
}

pub fn page_load_handler(win: &tauri::Webview, paylaod: &PageLoadPayload<'_>) {
    log::info!("page_load_handler:{}", win.label());

    // let mut downloaded = 0;
    // // alternatively we could also call update.download() and update.install() separately
    // update
    //     .download_and_install(
    //         |chunk_length, content_length| {
    //             downloaded += chunk_length;
    //             log::info!("downloaded {downloaded} from {content_length:?}");
    //         },
    //         || {
    //             log::info!("download finished");
    //         },
    //     )
    //     .await?;

    // log::info!("update installed");
    // app.restart();
}
